import { defineStore } from "pinia";
import { ref } from "vue";
import { loginAPI } from '@/api/user'
import { useCartStore } from "./cartStore";
import { checkCartAPI } from "@/api/cart";

export const useUserStore = defineStore('user',() =>{
  const cartStore = useCartStore()
  const userInfo = ref({})

  const getUserInfo = async ({ account, password }) =>{
    const res = await loginAPI({ account, password })
    userInfo.value = res.result

    await checkCartAPI(cartStore.cartList.map(item => {
      return {
        skuId: item.skuId,
        selected: item.selected,
        count: item.count
      }
    }))
    const res2 = await cartStore.findNewCartListAPI()
    cartStore.cartList = res2.result
  }
  const clearUserInfo = () =>{
    userInfo.value = {}
    cartStore.clearCart()
  }
  return {
    userInfo,
    getUserInfo,
    clearUserInfo
  }
},{
  // pinia设置自动本地存储
  persist: true
})